const pty = require("node-pty");

const ppy_pty = (ctx) => {
    let term;
    try{
        term = pty.spawn('bash', ["--login"], {
            name: "xterm-256color",
            cols: 80,
            rows: 24,
            cwd: process.env.HOME,//__dirname
            env: process.env,
        });
    }catch(err){
        ctx.websocket.send('创建控制台异常');
        return;
    }

    term.on("data", (data) => {
        ctx.websocket.send(data);
    });

    term.on('exit', () => {
        term.kill()
        console.log('pty_term :: exit');
        ctx.websocket.close();
    });

    ctx.websocket.on('message', (data) => {
        term.write(data);
    });

    ctx.websocket.on('close', () => {
         console.log('pty_ws :: close');
        //const { pid } = term;
        //events.exited(0, pid);
        term.kill();
    });
}

module.exports = {
    ppy_pty
}
